# -*- coding: utf8 -*-

from bottle import abort, redirect
from bottle import route, get, post, request, response
from bottle import jinja2_view as jview
from utils import to_str, save_upload_file, to_time, now
from auth import CookieUser, authorized_only
from forms import *
from blog import *
from ui import create_pagination


@get('/admin/users/:userid#\d+#/delete/')
@post('/admin/users/:userid#\d+#/delete/')
@authorized_only(request, need_root=True)
@jview('admin/user_form')
def super_delete_user(userid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	target_user = BlogService().get_blog(userid=userid).get_owner()
	form = DeleteUserConfirmForm(request=request, submitlabel='确认删除')
	form.forwardlinks = (
		('/admin/users/%s/' % userid, u'取消并返回'),
	)
	if target_user.id == user.uid:
		form.result['result'] = False
		form.result['msg'] = u'你不能删除自己。'
	if form.validate() and target_user:
		if target_user.id != user.uid:
			target_user.get_blog().delete()
			form.result['result'] = True
			form.result['msg'] = u'用户 %s 已删除完成。' % target_user.username
			form.redirect = ('/admin/users/', u'稍后返回...')
	return {
		'user': user,
		'title': u'删除用户',
		'subtitle': u'删除用户: %s' % target_user.username if target_user else u'删除用户',
		'targetuser': target_user,
		'form': form,
		'back_link': {'url':'/admin/users/%s/' % userid, 'text':u'返回'}
	}


@get('/admin/users/:userid#\d+#/change_password/')
@post('/admin/users/:userid#\d+#/change_password/')
@authorized_only(request, need_root=True)
@jview('admin/user_form')
def super_change_user_password(userid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	target_user = BlogService().get_blog(userid=userid).get_owner()
	form = UserPasswordUpdateForm(request=request, submitlabel='修改')
	if target_user.id == user.uid:
		form.result['result'] = False
		form.result['msg'] = u'你不能在这里更改自己的密码。'
	if form.validate():
		data = form.data
		if target_user.id != user.uid:
			new_password = data['new_password']
			success, failmsg = target_user.change_password(new_password, 
				skip_current_password_check=True)
			if success:
				form.result['result'] = True
				form.result['msg'] = u'%s 的登录密码已修改。' % target_user.username
			else:
				form.result['msg'] = failmsg
	return {
		'user': user,
		'title': u'修改用户密码',
		'subtitle': u'修改用户密码',
		'targetuser': target_user,
		'form': form,
		'back_link': {'url':'/admin/users/%s/' % userid, 'text':u'返回'}
	}


@get('/admin/users/:userid#\d+#/settings/')
@post('/admin/users/:userid#\d+#/settings/')
@authorized_only(request, need_root=True)
@jview('admin/user_form')
def super_user_setting(userid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	target_user = BlogService().get_blog(userid=userid).get_owner()
	form = UserRoleAndStatusUpdatingForm(request=request, submitlabel=u'保存设定')
	if target_user.id == user.uid:
		form.result['result'] = False
		form.result['msg'] = u'你不能在这里更改自己的设置。'
	if form.validate():
		data = form.data
		if target_user.id != user.uid:
			target_user.domainname = data['domainname']
			target_user.isroot = 10 if data['isroot'] else 0
			target_user.status = 10 if data['enabled'] else 0
			target_user.update_settings()
			form.result['msg'] = u'%s 的设定已修改并保存。' % target_user.username
			form.result['result'] = True
			form.redirect = ('/admin/users/%s/' % target_user.id, u'正在返回...')
	if target_user and not request.POST:
		form.update_values({
			'domainname': target_user.domainname,
			'isroot': target_user.is_root_user,
			'enabled': target_user.enabled
		})
	return {
		'user': user,
		'title': u'修改用户设定',
		'subtitle': u'%s 用户设定' % target_user.username if target_user else u'修改用户角色',
		'targetuser': target_user,
		'form': form,
		'back_link': {'url':'/admin/users/%s/' % userid, 'text':u'返回'}
	}


@get('/admin/users/:userid#\d+#/')
@post('/admin/users/:userid#\d+#/')
@authorized_only(request, need_root=True)
@jview('admin/user_details')
def super_view_user_details(userid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	target_user = BlogService().get_blog(userid=userid).get_owner()
	return {
		'user': user,
		'title': u'用户信息',
		'subtitle': u'查看用户信息' if not target_user else target_user.username,
		'targetuser': target_user,
		'back_link': {'url':'/admin/users/', 'text':u'返回'}
	}


@get('/admin/users/')
@post('/admin/users/')
@authorized_only(request, need_root=True)
@jview('admin/users')
def super_list_users():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	users = BlogService().get_users()
	return {
		'user': user,
		'title': u'所有用户',
		'subtitle': u'用户管理',
		'users': users
	}


# -----------------------------------------------


@get('/admin/links/:linkid#\d+#/delete/')
@post('/admin/links/:linkid#\d+#/delete/')
@authorized_only(request)
@jview('admin/form')
def link_delete(linkid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	form = LinkDeleteConfirmForm(request=request, submitlabel='删除')
	link = blog.get_link(linkid)
	if form.validate() and link:
		link.delete()
		form.result['result'] = True
		form.result['msg'] = u'指定的链接的已删除。'
		form.redirect = ('/admin/links/', u'正在返回...')
	return {
		'user': user,
		'title': u'链接修改',
		'subtitle': u'链接修改',
		'form': form,
		'back_link': {'url':'/admin/links/', 'text':u'返回'}
	}

@get('/admin/links/:linkid#\d+#/edit/')
@post('/admin/links/:linkid#\d+#/edit/')
@authorized_only(request)
@jview('admin/form')
def link_edit(linkid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	form = LinkEditForm(request=request, submitlabel='保存修改')
	link = blog.get_link(linkid)
	if form.validate() and link:
		data = form.data
		link.listindex = data['listindex']
		link.label = data['label']
		link.url = data['url']
		link.highlight = 1 if data['highlight'] else 0
		link.linkdesc = data['linkdesc']
		link.save()
		form.result['result'] = True
		form.result['msg'] = u'链接的已保存。'
		form.redirect = ('/admin/links/', u'正在返回...')
	if link and not request.POST:
		form.update_values({
			'label': link.label,
			'url': link.url,
			'highlight': link.is_highlight,
			'linkdesc': link.linkdesc,
			'listindex': link.listindex
		})
	return {
		'user': user,
		'title': u'链接修改',
		'subtitle': u'链接修改',
		'form': form,
		'back_link': {'url':'/admin/links/', 'text':u'返回'}
	}

@get('/admin/links/new/')
@post('/admin/links/new/')
@authorized_only(request)
@jview('admin/form')
def create_new_link():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	form = LinkEditForm(request=request, submitlabel='添加')
	if form.validate():
		data = form.data
		link = SidebarLink()
		link.userid = blog.get_owner().id
		link.listindex = data['listindex']
		link.label = data['label']
		link.url = data['url']
		link.highlight = 1 if data['highlight'] else 0
		link.linkdesc = data['linkdesc']
		link.position = 0
		link.save()
		form.result['result'] = True
		form.result['msg'] = u'链接已添加。'
		form.redirect = ('/admin/links/', u'正在返回...')
	return {
		'user': user,
		'title': u'添加链接',
		'subtitle': u'添加链接',
		'form': form,
		'back_link': {'url':'/admin/links/', 'text':u'返回'}
	}

@get('/admin/links/')
@post('/admin/links/')
@authorized_only(request)
@jview('admin/links')
def list_links():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	links = blog.get_links()
	return {
		'user': user,
		'title': u'友情链接管理',
		'subtitle': u'友情链接管理',
		'links': links
	}
	

@get('/admin/categories/:categoryid#\d+#/delete/')
@post('/admin/categories/:categoryid#\d+#/delete/')
@authorized_only(request)
@jview('admin/form')
def delete_category(categoryid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	bloguser = blog.get_owner()
	category = blog.get_category(categoryid=categoryid)
	form = CategoryDeleteConfirmForm(request=request, submitlabel=' 确认删除 ')
	if form.validate() and category:
		category.delete()
		form.result['result'] = True
		form.result['msg'] = u'指定的栏目已删除完成。'
		form.redirect = ('/admin/categories/', u'正在返回...')
	return {
		'user': user,
		'title': u'删除栏目',
		'subtitle': u'删除栏目',
		'form': form,
		'back_link': {'url':'/admin/categories/', 'text':u'返回'}
	}

@get('/admin/categories/:categoryid#\d+#/edit/')
@post('/admin/categories/:categoryid#\d+#/edit/')
@authorized_only(request)
@jview('admin/form')
def edit_category(categoryid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	blog = BlogService().get_blog(userid=user.uid)
	bloguser = blog.get_owner()
	category = blog.get_category(categoryid=categoryid)
	form = CategorySettingsForm(request=request, submitlabel=' 保存 ')
	if form.validate() and category:
		data = form.data
		category.categoryname = data['categoryname']
		category.listindex = data['listindex'] 
		category.save()
		form.result['result'] = True
		form.result['msg'] = u'栏目设置已修改并保存。'
		form.redirect = ('/admin/categories/', u'正在返回...')
	if category and not request.POST:
		form.update_values({
			'categoryname': category.categoryname,
			'listindex': category.listindex
		})
	return {
		'user': user,
		'title': u'修改栏目设置',
		'subtitle': u'修改栏目设置',
		'form': form,
		'back_link': {'url':'/admin/categories/', 'text':u'返回'}
	}


@get('/admin/categories/new/')
@post('/admin/categories/new/')
@authorized_only(request)
@jview('admin/form')
def create_new_category():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	form = CategorySettingsForm(request=request, submitlabel=' 创建 ')
	if form.validate() and bloguser:
		data = form.data
		category = Category()
		category.userid = bloguser.id
		category.categoryname = data['categoryname']
		category.listindex = data['listindex'] 
		category.postcount = 0
		category.save()
		form.result['result'] = True
		form.result['msg'] = u'栏目已成功创建。'
		form.redirect = ('/admin/categories/', u'正在返回...')
	return {
		'user': user,
		'title': u'新建栏目',
		'subtitle': u'新建栏目',
		'form': form,
		'back_link': {'url':'/admin/categories/', 'text':u'返回'}
	}


@get('/admin/categories/')
@post('/admin/categories/')
@authorized_only(request)
@jview('admin/categories')
def list_categories():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	categories = BlogService().get_blog(userid=user.uid).get_categories()
	return {
		'user': user,
		'title': u'栏目设置',
		'subtitle': u'栏目设置',
		'categories': categories
	}


@get('/admin/media/upload/')
@post('/admin/media/upload/')
@authorized_only(request)
def mediafile_upload():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	fail = True
	msg, url = '','/'
	uploadfile = request.files.get('imgFile')
	result = save_upload_file(uploadfile, 'static/media', createprefix=False)
	if result.has_key('fail'):
		msg = result['fail']
	else:
		url = '/static/media/%s' % result['filename']
		fail = False
		# blog = BlogService().get_blog(userid=user.uid)
	responsetext = '{"error":1, "message":"%s"}' % msg if fail else '{"error":0, "url":"%s"}' % url
	return responsetext


@get('/admin/posts/:postid#\d+#/delete/')
@post('/admin/posts/:postid#\d+#/delete/')
@authorized_only(request)
@jview('admin/form')
def delete_post(postid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	post = bloguser.get_blog().get_post(postid)
	form = PostDeleteConfirmForm(request=request, submitlabel='删除')
	form.forwardlinks = (('/admin/posts/', u'取消并返回'),)
	if form.validate() and post is not None:
		post.delete()
		form.result['result'] = True
		form.result['msg'] = u'文章已成功删除。'
		form.redirect = ('/admin/posts/', '稍后返回...')
	return {
		'user': user, 
		'title': u'删除文章', 
		'subtitle': u'删除文章: "%s"' % post.subject if post else u'删除文章',
		'form': form,
		'back_link': {'url':'/admin/posts/', 'text':u'返回'}
	}


@get('/admin/posts/:postid#\d+#/')
@post('/admin/posts/:postid#\d+#/')
@authorized_only(request)
@jview('admin/post_form')
def edit_exists_post(postid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	post = bloguser.get_blog().get_post(postid)
	form = PostEditForm(request=request, submitlabel=' 保存修改 ')
	category_choices = [(0, '默认')]
	category_choices.extend([(c.id, c.categoryname) for c in bloguser.get_blog().get_categories()])
	form.get_field('categoryid').choices = category_choices
	form.forwardlinks = []
	if post.published:
		form.forwardlinks.append(('/p/%s/' % post.id, u'浏览该文章'),)
	form.forwardlinks.append(('/admin/posts/', u'返回列表'),)
	if form.validate() and post is not None:
		data = form.data
		post.subject = data['subject']
		post.content = data['content']
		post.categoryid = data['categoryid']
		post.status = 0 if data['isdraft'] else 10
		post.lastmodified = to_time(now())
		post.save()
		form.result['result'] = True
		form.result['msg'] = u'文章已保存并发布。' if post.published else u'文章已存为草稿。'
		form.redirect = ('/admin/posts/', u'请稍等...')
	if not request.POST and post is not None:
		form.update_values({
			'subject': post.subject,
			'content': post.content,
			'isdraft': post.is_draft,
			'categoryid': post.categoryid
		})
	return {
		'user': user, 
		'title': u'编辑文章', 
		'subtitle': u'编辑文章',
		'form': form,
		'back_link': {'url':'/admin/posts/', 'text':u'返回'}
	}


@get('/admin/posts/draft/')
@post('/admin/posts/draft/')
@authorized_only(request)
@jview('admin/post_form')
def new_post():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	form = PostEditForm(request=request, submitlabel=' 保存 ')
	category_choices = [(0, '默认')]
	category_choices.extend([(c.id, c.categoryname) for c in bloguser.get_blog().get_categories()])
	form.get_field('categoryid').choices = category_choices
	form.forwardlinks = (('/admin/posts/', u'返回列表'),)
	if form.validate():
		data = form.data
		post = Post()
		post.subject = data['subject']
		post.content = data['content']
		post.categoryid = data['categoryid']
		post.status = 0 if data['isdraft'] else 10
		post.subjecturl = ''
		post.frontphoto = ''
		post.createdate = to_time(now())
		post.commentcount = 0
		post.lastmodified = post.createdate
		post.allowcomment = 1
		post.highlight = 0
		post.upvote = 0
		post.downvote = 0
		post.userid = bloguser.id
		post.save()
		form.result['result'] = True
		form.result['msg'] = u'文章已保存并发布。' if post.published else u'文章已存为草稿。'
		form.redirect = ('/admin/posts/', u'请稍等...')
	return {
		'user': user, 
		'title': u'写新文章', 
		'subtitle': u'写新文章',
		'form': form,
		'back_link': {'url':'/admin/posts/', 'text':u'返回'}
	}


@get('/admin/posts/')
@post('/admin/posts/')
@authorized_only(request)
@jview('admin/posts')
def list_posts():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	service = BlogService()
	blog = service.get_blog(userid=user.uid)
	pageindex = request.GET.get('page') or ''
	pageindex = 1 if not pageindex.isdigit() else int(pageindex)
	posts, has_more = blog.get_posts(page=pageindex, pagesize=16)
	pagemarks = create_pagination(current=pageindex, has_more_pages=has_more)
	return {
		'user': user, 
		'title': u'文章管理', 
		'subtitle': u'文章',
		'posts': posts,
		'pagemarks': pagemarks
	}


@get('/admin/comments/:commentid#\d+#/delete/')
@post('/admin/comments/:commentid#\d+#/delete/')
@authorized_only(request)
@jview('admin/form')
def delete_comment(commentid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	service = BlogService()
	blog = service.get_blog(userid=user.uid)
	comment = blog.get_comment(commentid)
	form = CommentDeleteConfirmForm(request=request, submitlabel='删除此条评论')
	if comment:
		hint_text = u'确认删除此条由 %s 发布于 %s 的评论？' % (comment.author, comment.createdate_dt)
		form.get_field('confirmtext').text = hint_text
	form.forwardlinks = (('/admin/comments/', u'取消并返回'),)
	if form.validate() and comment is not None:
		comment.delete()
		# try to recount the comment count of the post
		post = blog.get_post(postid=comment.postid)
		if post:
			post.recount_comments_count()
		form.result['result'] = True
		form.result['msg'] = u'指定的评论已成功删除。'
		form.redirect = ('/admin/comments/', '稍后返回...')
	return {
		'user': user, 
		'title': u'删除评论', 
		'subtitle': u'删除评论',
		'form': form,
		'back_link': {'url':'/admin/comments/', 'text':u'返回'}
	}


@get('/admin/comments/:commentid#\d+#/')
@post('/admin/comments/:commentid#\d+#/')
@authorized_only(request)
@jview('admin/view_comment')
def view_single_comment(commentid):
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	service = BlogService()
	blog = service.get_blog(userid=user.uid)
	comment = blog.get_comment(commentid)
	post = None
	all_comments = None
	if comment:
		if comment.postid:
			post = blog.get_post(comment.postid)
			all_comments, has_more = post.get_comments(page=0, pagesize=0)
	return {
		'user': user, 
		'title': u'浏览评论', 
		'subtitle': u'浏览评论',
		'comment': comment,
		'post': post,
		'all_comments': all_comments,
		'back_link': {'url':'/admin/comments/', 'text':u'返回'}
	}

@get('/admin/comments/')
@post('/admin/comments/')
@authorized_only(request)
@jview('admin/comments')
def list_comments():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	service = BlogService()
	blog = service.get_blog(userid=user.uid)
	pageindex = request.GET.get('page') or ''
	pageindex = 1 if not pageindex.isdigit() else int(pageindex)
	comments, has_more = blog.get_comments(page=pageindex, pagesize=16)
	pagemarks = create_pagination(current=pageindex, has_more_pages=has_more)
	return {
		'user': user, 
		'title': u'评论管理', 
		'subtitle': u'评论',
		'comments': comments,
		'pagemarks': pagemarks
	}


@get('/admin/password_update/')
@post('/admin/password_update/')
@authorized_only(request)
@jview('admin/form')
def password_update():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	form = PasswordUpdateForm(request=request, submitlabel=u'保存设置')
	if form.validate():
		data = form.data
		current_password = data['current_password']
		new_password = data['new_password']
		success, msg = bloguser.change_password(new_password=new_password, 
			current_password=current_password,
			skip_current_password_check=False)
		if success:
			form.result['result'] = True
			form.result['msg'] = u'你的登录密码已成功修改。'
		else:
			form.result['msg'] = msg if msg else u'密码修改失败。'
	return {
		'user': user, 
		'title': u'修改密码', 
		'subtitle': u'修改登录密码',
		'form': form
	}


@get('/admin/settings/')
@post('/admin/settings/')
@authorized_only(request)
@jview('admin/form')
def user_settings():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	bloguser = BlogService().get_blog(userid=user.uid).get_owner()
	form = UserSettingsForm(request=request, submitlabel=u'保存设置')
	if form.validate():
		data = form.data
		bloguser.domainname = data['domainname']
		bloguser.namealias = data['namealias']
		bloguser.fullname = data['fullname']
		bloguser.email = data['email']
		bloguser.theme = data['theme']
		bloguser.update_settings()
		form.result['result'] = True
		form.result['msg'] = u'你的设置已经保存。'
	if not request.POST:
		form.update_values({
			'domainname': bloguser.domainname,
			'namealias': bloguser.namealias,
			'fullname': bloguser.fullname,
			'email': bloguser.email,
			'theme': bloguser.theme or ''
		})
	return {
		'user': user, 
		'title': u'个人设置', 
		'subtitle': u'个人设置',
		'form': form
	}

@get('/admin/signin/')
@post('/admin/signin/')
@jview('admin/signin')
def signin():
	user = CookieUser(request=request, response=response)
	if user.authenticated:
		return {'user': user, 'title':u'你已经登录', 'subtitle':u'已经登录'}
	form = SignInForm(request=request, submitlabel=u'登录')
	if form.validate():
		data = form.data
		success,blog_user = BlogUser.authenticate(data['username'], data['password'])
		if success:
			user.isroot = blog_user.isroot > 0
			user.save(blog_user.id, blog_user.username)
			form.result['msg'] = u'欢迎登录。'
			form.result['result'] = True
			form.redirect = ('/admin/',u'请稍等...')
		else:
			form.result['msg'] = u'用户名或者密码有错。'
	return {
		'user': user, 
		'title': u"登录",
		'subtitle': 'Sign In',
		'form': form
	}

@get('/admin/signout/')
@jview('admin/signout')
def signout():
	user = CookieUser(request=request, response=response)
	user.clear()
	return {'user':user, 'title':u'退出登录', 'signout_ok':True}


@get('/admin/need_authorization/')
@post('/admin/need_authorization/')
@jview('admin/access_denied')
def need_authorization():
	user = request.user if hasattr(request, 'user') else CookieUser(request=request)
	return {'title':u'拒绝访问', 'user': user}

	
@route('/admin/')
@jview('admin/index')
def index():
	user = CookieUser(request=request)
	if not user.authenticated:
		return redirect('/admin/signin/')
	else:
		return {'user': user, 'title': "Welcome!", 'subtitle':'Welcome.'}




